package com.usian.cart.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.usian.cart.service.CartService;
import com.usian.jyzx.model.entity.user.UserInfo;
import com.usian.jyzx.model.vo.common.Result;
import com.usian.jyzx.model.vo.common.ResultCodeEnum;
import com.usian.jyzx.model.vo.h5.CartInfo;
import com.usian.jyzx.model.vo.h5.OrderItem;
import com.usian.jyzx.model.vo.h5.TradeVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 07 11 14 55
 **/
@RestController
@RequestMapping("/api/order")
@Slf4j
public class CartController {

    @Autowired
    CartService cartService;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/cart/auth/addToCart/{skuId}/{num}")
    public Result addCart(@PathVariable("skuId") Long skuId,
                          @PathVariable("num") Integer num, HttpServletRequest
request ){
        String token = request.getHeader("token");
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();

        cartService.addCart(userId,skuId,num);

        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());
    }

    @GetMapping("/cart/auth/cartList")
    public Result findCartList(HttpServletRequest
                                       request){

        String token = request.getHeader("token");
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();
        List<CartInfo> cartList = cartService.findCartList(userId);
        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),cartList);


    }

    @DeleteMapping ("/cart/auth/deleteCart/{skuId}")
    public Result delCart(@PathVariable("skuId") Long skuId,HttpServletRequest
            request){
        String token = request.getHeader("token");
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();
        cartService.delCart(userId,skuId);
        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());
    }




    @GetMapping("/cart/auth/checkCart/{skuId}/{isChecked}")
    public Result checkCart(HttpServletRequest request,
    @PathVariable("skuId") Long skuId,
                            @PathVariable("isChecked")   Integer isChecked){
        String token = request.getHeader("token");
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();
        cartService.checkCart(userId,skuId,isChecked);
        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());
    }

    @GetMapping("/cart/auth/allCheckCart/{isChecked}")
    public Result allcheckCart(HttpServletRequest request,
                               @PathVariable("isChecked")   Integer isChecked){

        String token = request.getHeader("token");
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();
        cartService.allcheckCart(userId,isChecked);
        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());
    }


    @GetMapping("/cart/auth/clearCart")
    public Result clearCart(HttpServletRequest request) {
        String token = request.getHeader("token");
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();
        cartService.clearCart(userId);
        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage());


    }


    @GetMapping("/cart/getAllOrderCkecked")
    public Result getAllOrderCkecked(String token){

        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();
        List<CartInfo> cartList = cartService.findCartList(userId);
        List<CartInfo> collect = cartList.stream().filter(
                cartInfo -> cartInfo.getIsChecked().intValue() == 1
        ).collect(Collectors.toList());

        log.info("collectcartList:{}",collect);

        /**
         * collect.stream()：将购物车商品列表转化为流。
         * .map(cartInfo -> cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())))：对每一个购物车商品，将其单价与数量相乘，得到每个商品的总价。
         * .reduce(BigDecimal.ZERO, BigDecimal::add)：将所有商品的总价相加，得到购物车中所有商品的总金额。
         * vo.setTotalAmount(...)：将计算得到的总金额设置到vo对象中。
         */

        List<OrderItem> orderItemList = new ArrayList<OrderItem>();
//Long skuId, Integer skuNum, String thumbImg, String skuName, Integer isChecked, BigDecimal skuPrice
        collect.forEach(cartInfo -> orderItemList.add(
                new OrderItem(
                        cartInfo.getSkuId(),
                        cartInfo.getSkuNum(),
                        cartInfo.getImgUrl(),
                        cartInfo.getSkuName(),
                        cartInfo.getIsChecked(),
                        cartInfo.getCartPrice()
                )
        ));

        TradeVo vo = new TradeVo();
        vo.setOrderItemList(orderItemList);
        //BigDecimal对象中的值相乘，返回BigDecimal对象  getCartPrice*SkuNum
        vo.setTotalAmount(collect.stream().map(
                cartInfo -> cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()))
        ).reduce(BigDecimal.ZERO, BigDecimal::add));

        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),vo);
    }



    @GetMapping("/orderInfo/auth/trade")

    public Result getAllCkecked(HttpServletRequest
                                            request){
        String token = request.getHeader("token");
        String str =(String) redisTemplate.opsForValue().get("token:" + token);

        UserInfo userInfo = JSON.parseObject(str, UserInfo.class);
        Integer userId = userInfo.getId();
        List<CartInfo> cartList = cartService.findCartList(userId);
        List<CartInfo> collect = cartList.stream().filter(
             cartInfo -> cartInfo.getIsChecked().intValue() == 1
        ).collect(Collectors.toList());

        log.info("collectcartList:{}",collect);

        /**
         * collect.stream()：将购物车商品列表转化为流。
         * .map(cartInfo -> cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())))：对每一个购物车商品，将其单价与数量相乘，得到每个商品的总价。
         * .reduce(BigDecimal.ZERO, BigDecimal::add)：将所有商品的总价相加，得到购物车中所有商品的总金额。
         * vo.setTotalAmount(...)：将计算得到的总金额设置到vo对象中。
         */

        List<OrderItem> orderItemList = new ArrayList<OrderItem>();
//Long skuId, Integer skuNum, String thumbImg, String skuName, Integer isChecked, BigDecimal skuPrice
         collect.forEach(cartInfo -> orderItemList.add(
                new OrderItem(
                        cartInfo.getSkuId(),
                        cartInfo.getSkuNum(),
                        cartInfo.getImgUrl(),
                        cartInfo.getSkuName(),
                        cartInfo.getIsChecked(),
                        cartInfo.getCartPrice()
                )
        ));

        TradeVo vo = new TradeVo();
        vo.setOrderItemList(orderItemList);
        //BigDecimal对象中的值相乘，返回BigDecimal对象  getCartPrice*SkuNum
        vo.setTotalAmount(collect.stream().map(
                cartInfo -> cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()))
        ).reduce(BigDecimal.ZERO, BigDecimal::add));

        return Result.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),vo);

    }


    @PostMapping("/order/delCart/{userId}")
    public void delCart(@PathVariable("userId") Integer userId,
                        @RequestBody List<Long> skuIdList) {
        if(CollUtil.isNotEmpty(skuIdList)){
            skuIdList.forEach(skuId -> cartService.delCart(userId,skuId));
        }


    }



}
